# backend/agents/chat_agent.py
"""
聊天智能体
"""

from typing import List, Dict, Any
from langchain.schema import BaseMessage
from ..models.base_model import BaseAIModel, AIModelResponse
import logging

logger = logging.getLogger(__name__)

class ChatAgent:
    """聊天智能体"""
    
    def __init__(self, model: BaseAIModel):
        self.model = model
        self.name = f"{model.provider}_{model.model_name}"
        self.conversation_memory = []
    
    async def generate_response(
        self, 
        messages: List[BaseMessage],
        **kwargs
    ) -> AIModelResponse:
        """生成响应"""
        try:
            # 确保模型已初始化
            if not self.model.llm:
                await self.model.initialize()
            
            # 生成响应
            response = await self.model.generate_response(messages, **kwargs)
            
            # 记录到对话记忆
            self.conversation_memory.extend(messages[-2:])  # 保留最近的问答
            
            logger.info(f"智能体 {self.name} 响应生成成功")
            return response
            
        except Exception as e:
            logger.error(f"智能体 {self.name} 响应生成失败: {e}")
            return AIModelResponse(
                content=f"抱歉，{self.name} 无法生成响应: {str(e)}",
                model_name=self.model.model_name,
                provider=self.model.provider,
                metadata={"error": str(e)}
            )
    
    async def stream_response(
        self, 
        messages: List[BaseMessage],
        **kwargs
    ):
        """流式生成响应"""
        try:
            if not self.model.llm:
                await self.model.initialize()
            
            async for chunk in self.model.stream_response(messages, **kwargs):
                yield chunk
                
        except Exception as e:
            logger.error(f"智能体 {self.name} 流式响应失败: {e}")
            yield f"抱歉，生成响应时出现错误: {str(e)}"
    
    def get_conversation_summary(self) -> str:
        """获取对话摘要"""
        if not self.conversation_memory:
            return "暂无对话记录"
        
        return f

    def get_conversation_summary(self) -> str:
        """获取对话摘要"""
        if not self.conversation_memory:
            return "暂无对话记录"
        
        return f"已进行 {len(self.conversation_memory)//2} 轮对话，使用模型: {self.model.model_name}"
    
    def clear_memory(self):
        """清空对话记忆"""
        self.conversation_memory.clear()
        logger.info(f"智能体 {self.name} 对话记忆已清空")